const Users = require("../models/user");
const Image = require("../models/image");
const router = require("koa-router")();
const uploadImage = require("../utils/uploadImg");
const mongoose = require("mongoose");

router.get("/info", async (ctx) => {
  let _id = ctx.state.user._id;
  let result = await Users.findOne({ _id })
    .select("_id username name email avatar type roles")
    .exec();
  ctx.body = result;
});

router.get("/images", async (ctx) => {
  let author = ctx.state.user._id;
  let type = ctx.request.query.type || "0";
  let result = await Image.find({ author, type });
  ctx.body = result;
});

router.post("/delImages", async (ctx) => {
  let _id = ctx.request.body.id;
  let author = ctx.state.user._id;
  console.log(_id, author);
  const res = await Image.deleteOne({ _id, author });
  ctx.body = res;
});

router.post("/uploadImage", async (ctx) => {
  try {
    const imageUrl = uploadImage(ctx);
    const author = ctx.state.user._id;
    const type = ctx.request.body.type;
    return (ctx.body = await Image.create({
      url: imageUrl,
      author: author,
      type,
      _id: mongoose.mongo.ObjectId(),
    }));
  } catch (e) {
    ctx.body = e;
  }
});

router.post("/updateImage", async (ctx) => {
  try {
    const author = ctx.state.user._id;
    const url = ctx.request.body.url;
    const type = ctx.request.body.type;
    ctx.body = await Image.create({
      url,
      author,
      type,
      _id: mongoose.mongo.ObjectId(),
    });
  } catch (e) {
    ctx.body = e;
  }
});

module.exports = router;
